package com.demoworld;

/**
 * Created by francis on 2017/7/5.
 * 这里使用单链表， 双链表会优化  每次pop查找上一个节点的方式
 */
public class JLinkedListStack implements IStack {
    public JLinkedListStack() {
        tail = null;
        head = null;
    }

    @Override
    public void push(int n) {
        JLinkedListStackNode node = new JLinkedListStackNode();
        node.value = n;
        if (this.isEmpty()) {//添加第一个元素
            tail = node;
            head = node;
            return;
        }
        if (head == tail) {
            head.next = node;
            tail = node;
            return;
        }
        tail.next = node;
        tail = node;
    }

    @Override
    public int pop() {
        if (this.isEmpty()) {
            return -1;//为了测试， 在push时 不要push -1
        }
        int n = tail.value;
        if (head == tail) {
            tail = null;
            head = null;
        } else {
            JLinkedListStackNode tmpPreNode = findPreNode(tail);
            tail = tmpPreNode;
        }
        return n;
    }

    private JLinkedListStackNode findPreNode(JLinkedListStackNode node) {
        if (this.isEmpty()) {
            return null;
        }

        JLinkedListStackNode tmpNode = head;
        boolean hasFound = false;
        while (true) {
            if (tmpNode.next == null) {
                tmpNode = null;
                break;
            }
            if (tmpNode.next == node) {
                hasFound = true;
                break;
            }
            tmpNode = tmpNode.next;
        }
        return tmpNode;
    }

    @Override
    public boolean isEmpty() {
        return (tail == null && head == null);
    }

    public JLinkedListStackNode tail;
    public JLinkedListStackNode head;


}
